/**
* @file osal_timer.c
* @brief OSAL timer manager 
* @details 
* @author huangbin
* @version V1.0.0
* @date 2025-04-25
* @copyright All documents are copyrighted by Shenzhen Xinlongwei Technology Co., LTD.
*            They may not be used for commercial purposes without permission
*/
#include "inc.h"


static OSAL_Timer timer[OSAL_TIMER_MAX];

void osalTimerInit( void )
{
    memset(timer, 0, sizeof(timer));
}
//设置一个任务级的超时定时器
//return: 任务id，失败的话返回 OSAL_TIMER_FAIL
uint32_t osalStartTimer( uint32_t task_id, uint32_t event_id,uint32_t timeout_value)
{
    uint32_t idx;
      
    //DISABLE_INTERRUPT();
    __IRQ_SAFE do 
    {
        if(timeout_value < OSAL_TIMER_10MS)
        {
            timeout_value = OSAL_TIMER_10MS;
        }

        for(idx = 0; idx < SIZEOF(timer); idx++)
        {
            if ((timer[idx].taskId == task_id) && (timer[idx].event & event_id))
            { 
                timer[idx].timeout_value = timeout_value; //如果这个事件id已经在该任务id存在，只更新超时时间
                break;
            }
        }
          
        if ( idx < SIZEOF(timer) )
        {
            //ENABLE_INTERRUPT();
            //return (idx >= SIZEOF(timer)) ? OSAL_TIMER_FAIL : task_id;
            break;
        }
          
        //创建一个新的定时器
        for(idx = 0; idx < SIZEOF(timer); idx++)
        {
            if(timer[idx].event == 0) //空定时位置找到
            {
                timer[idx].taskId = task_id;
                timer[idx].event = event_id;
                timer[idx].timeout_value = timeout_value;
                timer[idx].run = TRUE;
                break;
            }
        }
    } while(0);
    
    //ENABLE_INTERRUPT();

    return (idx >= SIZEOF(timer)) ? OSAL_TIMER_FAIL : task_id;
}
//停止任务级的超时定时器
uint32_t osalStopTimer(uint32_t task_id, uint32_t event_id)
{
    uint32_t idx;
      
    //DISABLE_INTERRUPT();
    __IRQ_SAFE {
        for(idx = 0; idx < SIZEOF(timer); idx++)
        {
            if((timer[idx].event & event_id) && (task_id == timer[idx].taskId))
            {
                memset( &timer[idx], 0, sizeof(timer[idx]));
                break;
            }
        }
    }
    //ENABLE_INTERRUPT();
    return (idx >= SIZEOF(timer)) ? OSAL_TIMER_FAIL : task_id;
}
    
void osalTimerIsr( uint32_t msTick )
{
    uint32_t idx;
      
    for ( idx = 0; idx < SIZEOF(timer); idx++)
    {
        if(timer[idx].run == FALSE ) { continue; }
        
        if(timer[idx].timeout_value > msTick )
        {
            timer[idx].timeout_value -= msTick;
        }
        else
        {
            timer[idx].timeout_value = 0;
            if(timer[idx].event != 0 )
            {
                taskEventsTable[timer[idx].taskId] |= timer[idx].event;  //把超时事件放到任务的事件表
                memset( &timer[idx], 0, sizeof(OSAL_Timer)); //清除定时器
            }
        }
    }
}
/************************END OF FILE*************************************/


